package com.sky.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.api.order.OrderFeignService;
import com.sky.constant.OrderStatus;
import com.sky.domain.WmsWareOrderTask;
import com.sky.domain.WmsWareOrderTaskDetail;
import com.sky.service.WmsWareOrderTaskDetailService;
import com.sky.service.WmsWareOrderTaskService;
import com.sky.mapper.WmsWareOrderTaskMapper;
import com.sky.service.WmsWareSkuService;
import com.sky.to.order.OmsOrderTo;
import com.sky.to.rabbitmq.StockLockTo;
import com.sky.utils.R;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
* @author Administrator
* @description 针对表【wms_ware_order_task(库存工作单)】的数据库操作Service实现
* @createDate 2024-06-30 16:47:16
*/
@Service
public class WmsWareOrderTaskServiceImpl extends ServiceImpl<WmsWareOrderTaskMapper, WmsWareOrderTask> implements WmsWareOrderTaskService{

    @Resource
    public OrderFeignService orderFeignService;
    @Resource
    private WmsWareOrderTaskDetailService wareOrderTaskDetailService;
    @Resource
    private WmsWareSkuService wareSkuService;

    /**
     * 进行订单库存解锁
     *
     * @param stockLockTo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean handleStockRelease(StockLockTo stockLockTo) {
        try {
            Long orderTaskId = stockLockTo.getOrderTaskId();
            WmsWareOrderTask wmsWareOrderTask = baseMapper.selectById(orderTaskId);

            List<Long> orderTaskDetailsIds = stockLockTo.getOrderTaskDetailsId();
            String orderSn = wmsWareOrderTask.getOrderSn();
            // 使用订单号查询订单状态
            R<OmsOrderTo> toR = orderFeignService.getInfoByOrderSn(orderSn);
            // 查询成功
            if (toR.getCode() == 0){
                OmsOrderTo data = toR.getData();
                int status = data.getStatus().intValue();
                // 订单生成成功
                if (data == null || status == OrderStatus.CLOSED.getCode() || status == OrderStatus.INVALID.getCode()){
                    // 下单失败,解锁库存
                    for (Long orderTaskDetailsId : orderTaskDetailsIds) {
                        WmsWareOrderTaskDetail detail = wareOrderTaskDetailService.getById(orderTaskDetailsId);
                        wareSkuService.unLockStock(detail);
                    }
                } else {
                    for (Long orderTaskDetailsId : orderTaskDetailsIds) {
                        WmsWareOrderTaskDetail detail = wareOrderTaskDetailService.getById(orderTaskDetailsId);
                        // 下单成功,扣减库存
                        wareSkuService.deductionStock(detail);
                    }
                }
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }
}




